package com.binhthuan.catechist.server.bus;

import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.binhthuan.catechist.server.domain.Account;
import com.binhthuan.catechist.server.util.HibernateUtil;

public class AccountBUS extends AbstractBUS {

    public Account getAccountById(int id) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        Account account = null;
        try {
            transaction = session.beginTransaction();
            account = (Account) session.get(Account.class, id);

            transaction.commit();
        } catch (HibernateException e) {
            transaction.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }

        return account;
    }

    public Account getAccountByUsername(String username) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        Account account = null;
        try {
            transaction = session.beginTransaction();
            Query query = session.createQuery("from Account where username = :username");
            query.setString("username", username);
            account = (Account) query.uniqueResult();

            if (account != null) {
                Hibernate.initialize(account.getTrainer());
                if (account.getTrainer() != null) {
                    Hibernate.initialize(account.getTrainer().getCurrentCourse());
                    if (account.getTrainer().getCurrentCourse() != null) {
                        Hibernate.initialize(account.getTrainer().getCurrentCourse().getYear());
                    }
                }
            }
            transaction.commit();
        } catch (HibernateException e) {
            transaction.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }

        return account;
    }

    public Account getAccountByEmail(String email) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        Account account = null;
        try {
            transaction = session.beginTransaction();
            Query query = session.createQuery("from Account where email = :email");
            query.setString("email", email);
            account = (Account) query.uniqueResult();

            transaction.commit();
        } catch (HibernateException he) {
            transaction.rollback();
            he.printStackTrace();
        } finally {
            session.close();
        }

        return account;
    }
}
